package org.example.tlias.controller;


import org.example.tlias.constant.MessageConstant;
import org.example.tlias.pojo.Emp;
import org.example.tlias.pojo.LoginInfo;
import org.example.tlias.pojo.Result;
import org.example.tlias.services.EmpService;
import org.example.tlias.utils.JwtProperties;
import org.example.tlias.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
public class LoginController {

    @Autowired
    EmpService empService;
    @Autowired
    JwtProperties jwtProperties;

    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {

        LoginInfo info = empService.login(emp);
        if(info != null){
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", info.getId());
            info.setToken(JwtUtils.createJwt(jwtProperties.getSecretKey(), jwtProperties.getTtlMillis(), claims));
            return Result.success(info);
        }

        return Result.error(MessageConstant.USERNAME_OR_PASSWORD_ERROR);
    }
}
